package com.yn.service.zy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Lists;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yn.common.enums.*;
import com.yn.common.exception.TransitException;
import com.yn.common.model.article.ArticleTitleManage;
import com.yn.common.model.system.SystemCity;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.TCarFleetManageDO;
import com.yn.common.model.zy.TCarManageDO;
import com.yn.common.page.BasePage;
import com.yn.common.request.sc.CarFleetManageRequest;
import com.yn.common.request.sc.CarManageRequest;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.response.driver.DriverFleetDetailResponse;
import com.yn.common.response.driver.FleetManageDetailResponse;
import com.yn.common.response.driver.TCarManageResponse;

import com.yn.common.utils.PhoneValidator;
import com.yn.common.vo.CarFleetPageDrVO;
import com.yn.service.dao.zy.TCarFleetManageMapper;
import com.yn.service.dao.zy.TCarManageMapper;
import com.yn.service.service.SystemAttachmentService;
import com.yn.service.service.SystemCityService;
import com.yn.service.service.UserService;
import com.yn.service.zy.TCarFleetManageService;
import com.yn.service.zy.TCarManageService;
import com.yn.service.zy.model.dto.TCarFleetManageDTO;
import com.yn.service.zy.model.dto.TCarManageDTO;
import com.yn.service.zy.model.query.TCarFleetManageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service
@Slf4j
public class TCarFleetManageServiceImpl extends ServiceImpl<TCarFleetManageMapper, TCarFleetManageDO> implements TCarFleetManageService {

    @Resource
    private TCarFleetManageMapper tCarFleetManageMapper;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private TCarManageMapper tCarManageMapper;
    @Autowired
    private SystemCityService systemCityService;

    /**
     * 分页获取车队信息
     * @param query
     * @param basePage
     * @return
     */
    @Override
    public IPage<TCarFleetManageDO> listPage(TCarFleetManageQuery query, PageParamRequest basePage) {
        PageHelper.startPage(basePage.getPage(),basePage.getLimit());
        IPage<TCarFleetManageDO> page = new Page<>(basePage.getPage(),basePage.getLimit());

        LambdaQueryWrapper<TCarFleetManageDO> queryWrapper = Wrappers.lambdaQuery();

        if (!ObjectUtils.isEmpty(query)) {
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getCarFleetType()),TCarFleetManageDO::getFleetType,query.getCarFleetType());
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getAuditStatus()),TCarFleetManageDO::getAuditStatus,query.getAuditStatus());
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getPostStatus()),TCarFleetManageDO::getPostStatus,query.getPostStatus());
            queryWrapper.like(StringUtils.isNotBlank(query.getCarFleetName()),TCarFleetManageDO::getFleetName,query.getCarFleetName());
        }
        queryWrapper.eq(TCarFleetManageDO::getIsDelTag, BooleanEnum.NO.getCode());

        return tCarFleetManageMapper.selectPage(page,queryWrapper);
    }
    @Override
    public BasePage<TCarFleetManageDTO> listPage1(TCarFleetManageQuery query, PageParamRequest basePage) {
        PageHelper.startPage(basePage.getPage(),basePage.getLimit());
        LambdaQueryWrapper<TCarFleetManageDO> queryWrapper = Wrappers.lambdaQuery();
        if (!ObjectUtils.isEmpty(query)) {
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getCarFleetType()),TCarFleetManageDO::getFleetType,query.getCarFleetType());
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getAuditStatus()),TCarFleetManageDO::getAuditStatus,query.getAuditStatus());
            queryWrapper.eq(!ObjectUtils.isEmpty(query.getPostStatus()),TCarFleetManageDO::getPostStatus,query.getPostStatus());
            queryWrapper.like(StringUtils.isNotBlank(query.getCarFleetName()),TCarFleetManageDO::getFleetName,query.getCarFleetName());
        }
        queryWrapper.eq(TCarFleetManageDO::getIsDelTag, BooleanEnum.NO.getCode());
        List<TCarFleetManageDO> manageDOList = tCarFleetManageMapper.selectList(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(manageDOList)) {
            return BasePage.restPage(new ArrayList<>());
        }
        BasePage<TCarFleetManageDO> tCarFleetManageDOBasePage = BasePage.restPage(manageDOList);
        ArrayList<TCarFleetManageDTO> tCarFleetManageDTOS = new ArrayList<>(manageDOList.size());
        for (TCarFleetManageDO tCarFleetManageDO : manageDOList) {
            TCarFleetManageDTO dto = new TCarFleetManageDTO();
            BeanUtil.copyProperties(tCarFleetManageDO,dto);
            dto.setAuditStatusStr(AuditStatusEnum.getByCode(tCarFleetManageDO.getAuditStatus()).getName());
            dto.setPostStatusStr(PostStatusEnum.getByCode(tCarFleetManageDO.getPostStatus()).getName());
            dto.setFleetTypeStr(CarFleetTypeEnum.getByCode(tCarFleetManageDO.getFleetType()).getName());
            tCarFleetManageDTOS.add(dto);
        }
        BasePage<TCarFleetManageDTO> tCarFleetManageDTOBasePage = BasePage.restPage(tCarFleetManageDTOS);
        BeanUtils.copyProperties(tCarFleetManageDOBasePage, tCarFleetManageDTOBasePage,"list");
        return tCarFleetManageDTOBasePage;
    }

    @Override
    public List<TCarFleetManageDO> getInfoByAppUserId(Integer appUserId) {
        return lambdaQuery()
                .eq(TCarFleetManageDO::getAppUserId, appUserId)
                .eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode())
                .eq(TCarFleetManageDO::getIsDelTag, false)
                .list();
    }

    /**
     * 批量审核
     * @param cardFleetIds
     * @param auditStatus
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAudit(List<Integer> cardFleetIds, Integer auditStatus) {
        if (CollectionUtils.isEmpty(cardFleetIds)) {
            throw new TransitException("请选择要审核的数据");
        }
        if (ObjectUtils.isEmpty(auditStatus) ||
                !Arrays.stream(AuditStatusEnum.values()).map(AuditStatusEnum::getCode).collect(Collectors.toList()).contains(auditStatus)) {
            throw new TransitException("审核无效，请联系管理员");
        }

        List<TCarFleetManageDO> tCarFleetManageDOList = Lists.newArrayList();

          /*  // 获取要审核的数据信息
            LambdaQueryWrapper<TCarFleetManageDO> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(TCarFleetManageDO::getId,cardFleetIds);
            queryWrapper.eq(TCarFleetManageDO::getIsDelTag,BooleanEnum.NO.getCode());
            List<TCarFleetManageDO> tCarFleetManageDOListByIds = tCarFleetManageMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(tCarFleetManageDOListByIds)) {
                throw new TransitException("未获取到审核的数据");
            }*/

        cardFleetIds.forEach(item -> {
            TCarFleetManageDO tCarFleetManageDO = new TCarFleetManageDO();
            tCarFleetManageDO.setId(item);
            tCarFleetManageDO.setAuditStatus(auditStatus);
            tCarFleetManageDOList.add(tCarFleetManageDO);
        });

        updateBatchById(tCarFleetManageDOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//这里要操纵两张表 user表和当前表
    public void saveFleet(CarFleetManageRequest request) {
        /*if(Objects.equals(request.getFleetType(), CarFleetTypeEnum.PERSONAL.getCode())){
            throw new TransitException("创建异常");
        }*/
        //判断图片url，运营资格材料url是否存在于数据库中 可能是由逗号分隔的多个url
        String fleetImageUrls = request.getFleetImageUrl();
        boolean isImagesExist = checkImageUrl(fleetImageUrls);
        //上传附件也只会保存压缩图片路径，不会保存附件路径 详见：UploadServiceImpl 第361行
        String materialUrls = request.getOperationMaterial();
        boolean isMaterialExist = checkImageUrl(materialUrls);
        if(!isImagesExist || !isMaterialExist){
            throw new TransitException("附件或者图片路径不正确");
        }
        //检测负责人手机号是否合规
        boolean isValid = PhoneValidator.isValid(request.getFleetCuratorPhonenumber());
        if(!isValid){
            throw new TransitException("负责人手机号不合规");
        }
        //获取当前登录用户id，判断是后台添加还是用户添加
        //按照车长电话号码尝试获取用户信息
        List<TCarFleetManageDO> list = lambdaQuery().eq(TCarFleetManageDO::getFleetName, request.getFleetName()).list();
        if(CollUtil.isNotEmpty(list)){
            throw new TransitException("车队名称已存在,请换一个车队名称");
        }
        TCarFleetManageDO tCarFleetManageDO = new TCarFleetManageDO();
        //获取当前用户id
        User user = userService.getInfoException();
        //判断当前用户是否绑定车队，绑定车队支支持一对一
        TCarFleetManageDO one = lambdaQuery().eq(TCarFleetManageDO::getAppUserId, user.getUid()).one();
        if(one!=null){
            throw new TransitException("当前用户已绑定车队");
        }
        //用户自己注册
        if(user.getUid()!=null){
            tCarFleetManageDO.setCreateId(user.getUid());
            tCarFleetManageDO.setUpdateId(user.getUid());
        }
        user.setIdentity(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode());
        tCarFleetManageDO.setAppUserId(user.getUid());
        /*User one = userService.getByPhone(request.getFleetCuratorPhonenumber());
        if(one==null){
            //创建新用户，并将其身份与车队进行绑定
            User user = new User();
            user.setIdentity(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode());
            user.setPhone(request.getFleetCuratorPhonenumber());
            user.setCardId(request.getFleetCuratorIdNumber());
            user.setRealName(request.getFleetCuratorName());
            user.setAccount(request.getFleetCuratorPhonenumber());
            userService.save(user);
            //将用户信息加到tCarFleetManageDO
            tCarFleetManageDO.setAppUserId(user.getUid());
        }else if(!Objects.equals(one.getIdentity(), UserIdentityEnum.ORDINARY_USER.getCode())){
            //如果用户不是普通用户
            throw new TransitException("用户已存在,请更换手机号");
        }else{
            //用户存在，且是普通用户，那就将其身份改为车队入住人员并更新身份证，真实姓名
            one.setIdentity(UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode());
            one.setCardId(request.getFleetCuratorIdNumber());
            one.setRealName(request.getFleetCuratorName());
            userService.updateById(one);
            //将用户信息加到tCarFleetManageDO
            tCarFleetManageDO.setAppUserId(one.getUid());
        }*/

        tCarFleetManageDO.setFleetName(request.getFleetName());
        tCarFleetManageDO.setFleetImageUrl(request.getFleetImageUrl());
        tCarFleetManageDO.setFleetIntro(request.getFleetIntro());
        tCarFleetManageDO.setFleetCuratorName(request.getFleetCuratorName());
        tCarFleetManageDO.setFleetCuratorPhonenumber(request.getFleetCuratorPhonenumber());
        tCarFleetManageDO.setFleetCuratorIdNumber(request.getFleetCuratorIdNumber());
        tCarFleetManageDO.setOperationMaterial(request.getOperationMaterial());
        tCarFleetManageDO.setRegionCode(request.getRegionCode());
        tCarFleetManageDO.setFleetAddress(request.getFleetAddress());
        tCarFleetManageDO.setBankAccountName(request.getBankAccountName());
        tCarFleetManageDO.setBankCardNo(request.getBankCardNo());
        tCarFleetManageDO.setBankName(request.getBankName());
        tCarFleetManageDO.setBranchBank(request.getBranchBank());



        this.save(tCarFleetManageDO);
        }

    /**
     * 校验图片url是否存到数据库中——字符串
     * @param fleetImageUrls
     */
     public boolean checkImageUrl(String fleetImageUrls) {
        String[] images = fleetImageUrls.split(",");
        boolean exists=false;
        for (String imageUrl : images) {
           exists=  systemAttachmentService.selectByUrl(imageUrl);
          if(!exists){
              return false;
          }
        }
        return exists;
    }
    /**
     * 校验图片url是否存到数据库中——集合
     * @param fleetImageUrls
     */
    public boolean checkImageUrl(List<String> fleetImageUrls) {
        boolean exists=false;
        for (String imageUrl : fleetImageUrls) {
            exists=  systemAttachmentService.selectByUrl(imageUrl);
            if(!exists){
                return false;
            }
        }
        return exists;
    }

    @Override
    public PageInfo<CarFleetPageDrVO> drListPage(String carFleetName, String keyWords, PageParamRequest pageParamRequest) {
        com.github.pagehelper.Page<ArticleTitleManage> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<TCarFleetManageDO> lambdaQuery = Wrappers.lambdaQuery();
        //司机端只能查看在岗的，审核通过的，车队类型为2的
        lambdaQuery.eq(TCarFleetManageDO::getFleetType, CarFleetTypeEnum.CAR_FLEET.getCode());
        lambdaQuery.eq(TCarFleetManageDO::getPostStatus, PostStatusEnum.IN_SERVICE.getCode());
        lambdaQuery.eq(TCarFleetManageDO::getAuditStatus, AuditStatusEnum.PASS.getCode());
        if(carFleetName != null && !carFleetName.isEmpty()){
            lambdaQuery.eq(TCarFleetManageDO::getFleetName, carFleetName);
        }
        if(keyWords != null&& !keyWords.isEmpty()){
            lambdaQuery.and(i -> i.or().like(TCarFleetManageDO::getFleetName, keyWords)
                    .or().like(TCarFleetManageDO::getFleetIntro, keyWords));
        }
        List<TCarFleetManageDO> tCarFleetManageDOS = baseMapper.selectList(lambdaQuery);
        ArrayList<CarFleetPageDrVO> list = new ArrayList<>();
        if(tCarFleetManageDOS == null || tCarFleetManageDOS.size() < 1){
            return BasePage.copyPageInfo(articlePage, list);
        }
        for (TCarFleetManageDO tCarFleetManageDO : tCarFleetManageDOS) {
            CarFleetPageDrVO carFleetPageDrVO = new CarFleetPageDrVO();
            carFleetPageDrVO.setId(tCarFleetManageDO.getId());
            carFleetPageDrVO.setFleetName(tCarFleetManageDO.getFleetName());
            carFleetPageDrVO.setFleetImageUrl(tCarFleetManageDO.getFleetImageUrl());
            carFleetPageDrVO.setFleetIntro(tCarFleetManageDO.getFleetIntro());
            carFleetPageDrVO.setFleetCuratorName(tCarFleetManageDO.getFleetCuratorName());
            carFleetPageDrVO.setFleetCuratorPhoneNumber(tCarFleetManageDO.getFleetCuratorPhonenumber());
            carFleetPageDrVO.setCreateTime(tCarFleetManageDO.getCreateTime());
            list.add(carFleetPageDrVO);
        }
        return BasePage.copyPageInfo(articlePage, list);
    }

    /**
     * 管理端查询车队详情
    * */
    @Override
    public TCarFleetManageDTO selectById(Integer id) {
        TCarFleetManageDO byId = this.getById(id);
        TCarFleetManageDTO dto = TCarFleetManageDTO.transform(byId);

        LambdaQueryWrapper<TCarManageDO> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TCarManageDO::getFleetManageId, id);
        List<TCarManageDO> list = tCarManageMapper.selectList(lambdaQuery);
        if(CollectionUtils.isEmpty(list)){
            dto.setCarManageDTOList(new ArrayList<>());
        }else{
            ArrayList<TCarManageResponse> manageResponseList = new ArrayList<>();
            for (TCarManageDO tCarManageDO : list) {
                TCarManageResponse manageResponse = new TCarManageResponse();
                BeanUtil.copyProperties(tCarManageDO, manageResponse);
                manageResponseList.add(manageResponse);
            }
            dto.setCarManageDTOList(manageResponseList);
        }
        return dto;
    }

    /**
     * 司机端查询车队详情
    * */
    @Override
    public FleetManageDetailResponse getFleetDetailInfo(Integer id) {
        FleetManageDetailResponse response = new FleetManageDetailResponse();
        TCarFleetManageDO fleetInfo = getById(id);
        if(fleetInfo == null){
            throw new TransitException("车队不存在");
        }
        //获取当前用户，判断是管理员还是司机，管理员可以看任意车队的详细信息，司机只能看自己的
       /* User user = userService.getInfoException();
        if(!Objects.equals(user.getIdentity(), UserIdentityEnum.BACKGROUND_MANAGER.getCode()) && !Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
            throw new TransitException("您没有权限查看该车队信息");
        }
        if(!Objects.equals(user.getUid(), fleetInfo.getAppUserId()) && Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
            throw new TransitException("您没有权限查看该车队信息");
        }*/
        User user = userService.getInfo();
        if(user!=null){
            if(!Objects.equals(user.getIdentity(), UserIdentityEnum.FLEET_ENTRY_PERSONNEL.getCode())){
                throw new TransitException("您没有权限查看该车队信息");
            }
            if(!Objects.equals(user.getUid(), fleetInfo.getAppUserId())){
                throw new TransitException("您没有权限查看该车队信息");
            }
        }
        BeanUtil.copyProperties(fleetInfo, response);
        //获取车队类型
        Integer fleetType = fleetInfo.getFleetType();
        CarFleetTypeEnum byCode = CarFleetTypeEnum.getByCode(fleetType);
        response.setFleetTypeStr(byCode.getName());
        //获取审核状态
        Integer auditStatus = fleetInfo.getAuditStatus();
        AuditStatusEnum byCode1 = AuditStatusEnum.getByCode(auditStatus);
        response.setAuditStatusStr(byCode1.getName());
        //地区编码字符
        String regionCode = fleetInfo.getRegionCode();
        SystemCity cityByAreaCode = systemCityService.getCityByAreaCode(regionCode);
        response.setRegionCodeStr(cityByAreaCode.getName());
        //岗位状态
        Integer postStatus = fleetInfo.getPostStatus();
        PostStatusEnum byCode2 = PostStatusEnum.getByCode(postStatus);
        response.setPostStatusStr(byCode2.getName());
        return response;
    }

    @Override
    @Transactional
    public void saveCar(CarManageRequest request, Integer id) {
        //获取司机行驶证，驾驶证，保险证明以及电话号码用于校验
        String driverLicense = request.getDriverLicense();
        String drivingLicense = request.getDrivingLicense();
        String insuranceCertificate = request.getInsuranceCertificate();
        String carLinkNumber = request.getCarLinkNumber();
        boolean isDriverLicense =checkImageUrl(driverLicense);
        boolean isDrivingLicense = checkImageUrl(drivingLicense);
        boolean isInsuranceCertificate = checkImageUrl(insuranceCertificate);
        boolean isCarLinkNumber = checkImageUrl(carLinkNumber);
        if(!( isDriverLicense || isDrivingLicense || isInsuranceCertificate)){
            throw new TransitException("上传的证件有错误");
        }

        if(!isCarLinkNumber){
            throw new TransitException("上传的手机号有错误");
        }
        TCarFleetManageDO byId = getById(id);
        if(byId == null){
            throw new TransitException("要加入的车队信息有误");
        }
        if(byId.getAuditStatus() != 1){
            throw new TransitException("要加入的车队暂时不存在");
        }
        TCarManageDO tCarManageDO = new TCarManageDO();
        BeanUtil.copyProperties(request, tCarManageDO);
        tCarManageDO.setFleetManageId(id);
        tCarManageMapper.insert(tCarManageDO);
    }

    @Override
    public TCarFleetManageDO selectMyFleetInfoById(Integer id) {
        //获取当前用户手机号
        User user = userService.getInfoException();
        String phone = user.getPhone();
        TCarFleetManageDO byId = getById(id);
        if(byId == null){
            throw new TransitException("要查看的车队信息有误");
        }
        if(!phone.equals(byId.getFleetCuratorPhonenumber())){
            throw new TransitException("您没有权限查看此信息");
        }
        return byId;
    }




}
